<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/2 18:32
 * Modified Time: 2019/7/2 18:32
 * Version: 2.0
 */

namespace App\Modules\Inventory\Criterias;


use App\Lib\Utilities;
use App\Models\GoodsCategory;
use App\Models\Store;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class GoodsCategoryCriteria extends BaseCriterias
{
    protected $store_id;
    protected $type;
    protected $parent_id;

    public function __construct($store_id, $type, $parent_id = null)
    {
        $this->store_id = $store_id;
        $this->type = $type;
        $this->parent_id = $parent_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        $store_id = $this->store_id;
        $type = $this->type;
        $parent_id = $this->parent_id;

        if ($type == 1) {//全部

            $model = $model
                ->select([
                    'id',
                    'store_id',
                    'parent_id',
                    'name',
                    'status'
                ])
                ->with(['children' => function ($query) {
                    $query->select(['id', 'parent_id', 'name']);
                }])
                ->where('parent_id', 0)
                ->where('store_id', $store_id);


        } elseif ($type == 2) {//一级分类
            $model = $model
                ->select([
                    'id',
                    'store_id',
                    'parent_id',
                    'name',
                    'status'
                ])
                ->where('parent_id', 0)
                ->where('store_id', $store_id);

        } elseif ($type == 3) {//二级分类

            $model = $model
                ->select([
                    'id',
                    'store_id',
                    'parent_id',
                    'name',
                    'status'
                ])
                ->where('store_id', $store_id)
                ->where('parent_id', '<>', 0);

        } else {//某级分类下子分类

            $model = $model
                ->select([
                    'id',
                    'store_id',
                    'parent_id',
                    'name',
                    'status'
                ])
                ->where('store_id', $store_id)
                ->where('parent_id', $parent_id);

        }


        return $model;
    }
}